/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.annuaireComp.sessions;

import fr.annuaireComp.entities.Fonction;
import fr.annuaireComp.entities.Personnel;
import fr.annuaireComp.facades.PersonnelFacadeLocal;
import java.util.*;
import javax.ejb.EJB;
import javax.ejb.Stateless;

/**
 *
 * @author MiniK
 */
@Stateless
public class PersonnelManagerBean implements PersonnelManager, PersonnelManagerLocal {


    private static int DEFAULT_PERSONNEL_PASSWORD_LENGTH = 6;
    private static String ENTREPRISE_MAIL_DOMAIN = "@gestcomp.fr";
    
    @EJB
    private PersonnelFacadeLocal _DAL;

    
    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @Override
    public Personnel addPersonnel(String nom, String prenom, Date dateNaissance,  String bureau,boolean sexe, int idFonction) { 
        
        String email = nom + "." + prenom + ENTREPRISE_MAIL_DOMAIN;
        String password  = buildRandomPassword(DEFAULT_PERSONNEL_PASSWORD_LENGTH);
        Personnel p = new Personnel(null, nom, prenom, dateNaissance, sexe, email, password);
        p.setBureau(bureau);
        Fonction f = new Fonction(idFonction);
        p.setIdfonction(f);
        _DAL.create(p);
      
        return p;
    }

    
    
    @Override
    public void editPersonnel(Personnel personnel) {
         _DAL.edit(personnel);
    }

    @Override
    public Personnel getPersonnel(int idPersonnel)
    {
        return _DAL.find(idPersonnel);
    }

    @Override
    public List<Personnel> listPersonnels() {
        return _DAL.findAll();
    }

    @Override
    public void deletePersonnel(int idPersonnel) {
        Personnel perso = _DAL.find(idPersonnel);
        _DAL.remove(perso);
    }
    
    
    
    private String buildRandomPassword(int length)
    {
        Random rand = new Random();
        String alphaNum = "abcdefghijklmnopkrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String pw = "";
        while(pw.length() < length)
        {
            pw += alphaNum.charAt(rand.nextInt(alphaNum.length() -1));
        }
        
        return pw;
        
    }

    @Override
    public Personnel authenticatePersonnel(String email, String password) {
        Map<String,Object> criteria = new HashMap<String,Object>(2);
        criteria.put("email", email);
        criteria.put("password", password);
        
        List<Personnel> rez = _DAL.findBy(criteria);
        if(rez.size() != 1)
            return null;
        return rez.get(0);
    }

    @Override
    public List<Personnel> listPersonnelsBy(Map<String, Object> criteria) {
       if(criteria.isEmpty())
           return new ArrayList<Personnel>();
       
       List<Personnel> rez = _DAL.findBy(criteria);
       return rez;
    }
}
